﻿#include "MarkableImage.h"


MarkableImage::MarkableImage(QWidget *parent)
    : QLabel(parent), currentPointIndex(-1)
{
    setAlignment(Qt::AlignCenter);
    setMouseTracking(true);

    // 初始化标记点位置（这里需要根据实际图片调整坐标）
    pointPositions = {
        QPoint(42, 36), QPoint(92, 36), QPoint(142, 36),
        QPoint(67, 63), QPoint(117, 63),
        QPoint(47, 90),QPoint(92, 90), QPoint(142, 90),
        QPoint(67, 118),QPoint(117, 118),
        QPoint(42, 145), QPoint(92, 145),QPoint(142, 145)
    };
    // 初始化标记点标号
    pointLabels.fill(-1, 13);
}

void MarkableImage::setBackgroundImage(const QString &imagePath){
    originalPixmap.load(imagePath);
    update();
}

int MarkableImage::getCurrentPointIndex() const{
    return currentPointIndex;
}

QVector<int> MarkableImage::getAllPointLabels() const{
    return pointLabels;
}

void MarkableImage::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        // 检查点击位置是否接近某个标记点
        for (int i = 0; i < pointPositions.size(); ++i)
        {
            QPoint point = pointPositions[i];
            QPoint mousePos = event->pos();

            // 计算点击位置与标记点的距离
            int dx = mousePos.x() - point.x();
            int dy = mousePos.y() - point.y();
            int distance = dx * dx + dy * dy;

            // 如果距离小于阈值（10像素），则认为点击了该点
            if (distance < 100) // 10^2 = 100
            {
                currentPointIndex = i;
                pointLabels[i] = i; // 设置标号为点的索引

                // 重绘以更新标记点显示
                update();
                emit pointSelected(i); // 发出信号
                break;
            }
        }
    }

    QLabel::mousePressEvent(event);
}

void MarkableImage::paintEvent(QPaintEvent *event)
{
    QLabel::paintEvent(event);

    QPainter painter(this);
    // 绘制图片（带偏移量）
    painter.drawPixmap(imageOffset, originalPixmap);

    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制所有标记点
    for (auto i =0; i< pointPositions.size();i++)
    {
        QPoint absolutePos = pointPositions[i] + imageOffset;

        // 设置点的颜色（选中点为蓝色，未选中为灰色）
        if (i == currentPointIndex)
            painter.setBrush(Qt::blue);
        else
            painter.setBrush(QBrush("#7c7c7c"));

        // 绘制圆形标记点
        painter.drawEllipse(absolutePos, 7, 7);

        // 绘制标号
        painter.setPen(QColor("#7c7c7c"));
        painter.drawText(absolutePos.x()-2, absolutePos.y() + 17, QString::number(i+1));
    }
}
